/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.isfd.util;

import java.io.*;
import java.util.Arrays;
import java.net.URL;
import java.util.Objects;

import com.comac.ins.common.core.exception.base.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.core.io.ClassPathResource;


@Slf4j
public class ExecuteVbScript {
    private static final String exeFolder = "layupCalcVbScript";
    static String exePath;
    static {
        try {
            exePath = exeFolder + File.separator + "layupCalculation.exe";
            ClassPathResource resource = new ClassPathResource(exePath);
            File exeFile = resource.getFile();
            exePath = exeFile.getAbsolutePath();
            if (exePath.isEmpty()) {
                throw new BaseException("未找到计算文件");
            }
        } catch (Exception e){
            log.error("failed finding exePath",e);
        }
    }

    public static String saveFile(String folder) throws IOException {
        URL url = ExecuteVbScript.class.getClassLoader().getResource(folder);

        String fileFodlerPath = System.getProperty("user.dir");
        String targetPath = fileFodlerPath + File.separator + folder;
        File targetFolder = new File(targetPath);
        if (!targetFolder.exists()) {
            targetFolder.mkdirs();
        }

        // 处理文件系统资源
        File resourceDir = new File(url.getFile());
        if (resourceDir.isDirectory()) {
            // 遍历文件夹中的所有文件
            for (File file : Objects.requireNonNull(resourceDir.listFiles())) {
                // 提取文件
                String fileName = file.getName();
                String filePath = folder + File.separator + fileName;
                InputStream is = ExecuteVbScript.class.getClassLoader().getResourceAsStream(filePath);
                File targetFile = new File(targetFolder, file.getName());
                FileUtils.copyInputStreamToFile(is, targetFile);
            }
            exePath = targetPath + File.separator + "layupCalculation.exe";
        }

        return exePath;
    }

    public static double[] executeVbScript(double[]compositeMaterialProperties,
                                           double[] layerThicknessArray,
                                           int[] layupIntArray) {


        // 将数组转换为字符串
        String compositeMaterialPropertiesStr = Arrays.toString(compositeMaterialProperties).replaceAll("[\\[\\] ]", "");
        String layerThicknessArrayStr = Arrays.toString(layerThicknessArray).replaceAll("[\\[\\] ]", "");
        String layupIntArrayStr = Arrays.toString(layupIntArray).replaceAll("[\\[\\] ]", "");

        // 创建 ProcessBuilder 实例
        ProcessBuilder processBuilder = new ProcessBuilder(exePath, compositeMaterialPropertiesStr, layerThicknessArrayStr, layupIntArrayStr);
        processBuilder.redirectErrorStream(true); // 合并标准错误流到标准输出流
        if (exePath.isEmpty()) {
            throw new BaseException("未找到计算执行文件");
        }

        try {
            // 启动进程
            Process process = processBuilder.start();

            // 读取进程的输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            StringBuilder output = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                output.append(line);
            }

            // 等待进程结束并获取退出代码
            int exitCode = process.waitFor();
            System.out.println("Exited with code: " + exitCode);

            // 解析 output
            double[] equivalentProperties = parseDoubleArray(output.toString());
            return equivalentProperties;
        } catch (Exception e) {
            log.error("executeVbScript is fail",e);
            throw new BaseException("计算失败");
        }

    }
    // 将逗号分隔的字符串解析为 double 数组
    private static double[] parseDoubleArray(String input) {
        String[] stringArray = input.split(",");
        double[] doubleArray = new double[stringArray.length];
        for (int i = 0; i < stringArray.length; i++) {
            doubleArray[i] = Double.parseDouble(stringArray[i]);
        }
        return doubleArray;
    }

    public static void main(String[] args) {
        double [] compositeMaterialProperties = {157000, 9650, 0.31, 4600, 0.00000000154, -0.0000016, 0.0000513};
        double[] layerThicknessArray = {0, 0.187, 0.187, 0.187, 0.187, 0.187,
            0.187, 0.187, 0.187, 0.187, 0};
        int[] layupIntArray = {0, 45, 0, 0, -45, 90, -45, 0, 0, 45};
        double[] equivalentProperties = executeVbScript(compositeMaterialProperties, layerThicknessArray, layupIntArray);
        System.out.println("Equivalent Properties: " + Arrays.toString(equivalentProperties));
    }
}
